package com.example.activity;

import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.View;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.InfoWindowAdapter;
import com.amap.api.maps.AMap.OnInfoWindowClickListener;
import com.amap.api.maps.AMap.OnMapLoadedListener;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.example.consts.Consts;
import com.example.dianping.R;
import com.example.entity.Goods;
import com.example.entity.ResponseObject;
import com.example.entity.Shop;
import com.example.utils.ToastMaker;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

public class NearByActivity extends Activity implements LocationSource,
		AMapLocationListener, OnMarkerClickListener, OnMapLoadedListener,
		OnInfoWindowClickListener, InfoWindowAdapter {

	@ViewInject(R.id.mv_search_map)
	MapView mv_search_map;
	private AMap aMap;

	private double longitude = 116.394932;
	private double latitude = 39.949157;

	private LocationManagerProxy mAMapLocManager = null;
	private OnLocationChangedListener mListener;

	private List<Goods> listDatas;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_map_act);
		ViewUtils.inject(this);
		mv_search_map.onCreate(savedInstanceState);
		if (aMap == null) {
			aMap = mv_search_map.getMap();
			aMap.setLocationSource(this);
			aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
			aMap.setMyLocationEnabled(true);
			aMap.setOnMapLoadedListener(this);
			aMap.setOnMarkerClickListener(this);
			aMap.setInfoWindowAdapter(this);
			aMap.setOnInfoWindowClickListener(this);
		}

	}

	// Map Buttons onclick
	@OnClick({ R.id.iv_search_back, R.id.iv_search_reflush })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.iv_search_back:
			finish();
			break;
		case R.id.iv_search_reflush:
			loadData(String.valueOf(latitude), String.valueOf(longitude),
					"1000");
			break;
		default:
			break;
		}
	}

	// Load some shop location information
	/**
	 * @param lat
	 * @param lon
	 * @param raidus
	 *    
	 */
	private void loadData(String lat, String lon, String raidus) {
		RequestParams requestParams = new RequestParams();
		requestParams.addQueryStringParameter("lat", lat);
		requestParams.addQueryStringParameter("lon", lon);
		requestParams.addQueryStringParameter("raidus", raidus);

		new HttpUtils().send(HttpMethod.GET, Consts.Goods_NearBy_URI,
				requestParams, new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
//						ToastMaker
//								.showLongToast("Loading Data failed, plz try again!");
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						ResponseObject<List<Goods>> object = new GsonBuilder()
								.create()
								.fromJson(
										arg0.result,
										new TypeToken<ResponseObject<List<Goods>>>() {
										}.getType());
						listDatas = object.getDatas();

						aMap.animateCamera(CameraUpdateFactory
								.newCameraPosition(new CameraPosition(
										new LatLng(latitude, longitude), 16, 0,
										30)));
						addMarker(listDatas);
					}

				});
	}

	// Draw the shop icon on the map
	private void addMarker(List<Goods> listDatas) {
		MarkerOptions markerOptions;
		for (Goods goods : listDatas) {
			Shop shop = goods.getShop();
			markerOptions = new MarkerOptions();

			markerOptions.position(new LatLng(
					Double.parseDouble(shop.getLat()), Double.parseDouble(shop
							.getLon())));

			markerOptions.title(shop.getName()).snippet("￥" + goods.getPrice());
			if(goods.getCategoryId().equals("3")){
				markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_landmark_chi));
			}else if(goods.getCategoryId().equals("5")){
				markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_landmark_movie));
			}else if(goods.getCategoryId().equals("8")){
				markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_landmark_hotel));
			}else if(goods.getCategoryId().equals("6")){
				markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_landmark_life));
			}else if(goods.getCategoryId().equals("4")){
				markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_landmark_wan));
			}else{
				markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_landmark_default));
			}
			
			aMap.addMarker(markerOptions).setObject(goods);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		mv_search_map.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		mv_search_map.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mv_search_map.onDestroy();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mv_search_map.onSaveInstanceState(outState);
	}

	@Override
	public void activate(OnLocationChangedListener listener) {
		if (mAMapLocManager == null) {
			mListener = listener;
			mAMapLocManager = LocationManagerProxy.getInstance(this);
			mAMapLocManager.requestLocationData(
					LocationProviderProxy.AMapNetwork, 5000, 10, this);
		}
	}

	@Override
	public void deactivate() {
	}


	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
	}

	@Override
	public void onProviderEnabled(String provider) {
	}

	@Override
	public void onProviderDisabled(String provider) {
	}

	@Override
	public void onLocationChanged(AMapLocation location) {
		if (location != null) {
			location.setLatitude(latitude);
			location.setLongitude(longitude);
			longitude = location.getLongitude();
			latitude = location.getLatitude();
			System.out.println(longitude + "----" + latitude);
			mListener.onLocationChanged(location);
			
			loadData(latitude+"", longitude+"", "1000");
			mAMapLocManager.removeUpdates(this);
		}
	}

	@Override
	public void onMapLoaded() {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onMarkerClick(Marker arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onInfoWindowClick(Marker arg0) {
		String shopName = arg0.getTitle();
		Goods goods = getGoodsByShopName(shopName);
		
		if(goods != null){
			Intent intent = new Intent(this, GoodsDetailActivity.class);
			intent.putExtra("goods", goods);
			startActivity(intent);
		}
	}
	
	//Get the goods name to show on InfoWindow
	private Goods getGoodsByShopName(String shopName) {
		for (Goods goods : listDatas) {
			if(goods.getShop().getName().equals(shopName)){
				return goods;
			}
		}
		return null;
	}

	@Override
	public View getInfoContents(Marker arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public View getInfoWindow(Marker arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onLocationChanged(Location location) {
		
	}

}
